package com.yingxin.yxerp.module.organization.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yxerp.module.organization.entity.Department;
import com.yingxin.yxerp.module.organization.entity.DepartmentMgr;
import com.yingxin.yxerp.module.organization.entity.User;
import com.yingxin.yxerp.module.organization.mapper.DepartmentMgrMapper;
import com.yingxin.yxerp.module.organization.service.IDepartmentMgrService;
import com.yingxin.yxerp.module.organization.service.IDepartmentService;
import com.yingxin.yxerp.module.organization.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门负责人 服务实现类
 * @author fanchao
 * @since 2021-11-16
 */

@Service
public class DepartmentMgrServiceImpl
        extends ServiceImpl<DepartmentMgrMapper, DepartmentMgr>
        implements IDepartmentMgrService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IDepartmentService departmentService;

    @Override
    public List<DepartmentMgr> listByDeptId(String deptId) {
        QueryWrapper<DepartmentMgr> qw = new QueryWrapper<>();
        qw.lambda().eq(DepartmentMgr::getDeptId, deptId);
        return list(qw);
    }

    @Override
    public List<DepartmentMgr> recursionFindByDeptId(String deptId, String userId) {
        List<DepartmentMgr> mgrList = listByDeptId(deptId);
        if (CollectionUtil.isEmpty(mgrList)) {
            mgrList = findParent(deptId, userId);
        } else {
            for (DepartmentMgr mgr : mgrList) {
                if (mgr.getManagerId().equals(userId)) {
                    mgrList = findParent(deptId, userId);
                    break;
                }
            }
        }
        return mgrList;
    }

    private List<DepartmentMgr> findParent(String deptId, String userId) {
        Department parent = departmentService.getParentById(deptId);
        if (parent == null) {
            return new ArrayList<>();
        }
        List<DepartmentMgr> parentMrgList = listByDeptId(parent.getId());
        if (CollectionUtil.isEmpty(parentMrgList)) {
            parentMrgList = findParent(parent.getId(), userId);
        } else {
            for (DepartmentMgr mgr : parentMrgList) {
                if (mgr.getManagerId().equals(userId)) {
                    parentMrgList = findParent(parent.getId(), userId);
                    break;
                }
            }
        }
        return parentMrgList;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void updateDepartmentMgr(Department dept, List<String> managerIds) {
        deleteByDeptId(dept);
        StringBuilder deptMgrDesc = new StringBuilder();
        if (CollectionUtil.isNotEmpty(managerIds)) {
            for (String managerId : managerIds) {
                User user = userService.getById(managerId);
                create(dept, user);
                deptMgrDesc.append("[").append(user.getStaffName()).append("] ");
            }
        }
        dept.setDeptMgrDesc(deptMgrDesc.toString());
    }


    /**
     * 变更部门主管
     * @param dept 部门对象
     * @param dingManagerIds 钉钉主管userid 列表
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void updateDingDepartmentMgr(Department dept, List<String> dingManagerIds){
        deleteByDeptId(dept);
        StringBuilder deptMgrDesc = new StringBuilder();
        if ( CollectionUtil.isNotEmpty( dingManagerIds ) ) {
            for (String dingManagerId : dingManagerIds) {
                List<User> users = userService.checkIsDingUserId( dingManagerId );
                if( CollectionUtil.isNotEmpty( users ) ){
                    for( User user : users ){
                        create(dept, user);
                        deptMgrDesc.append("[").append(user.getStaffName()).append("] ");
                    }
                }
            }
        }
        dept.setDeptMgrDesc(deptMgrDesc.toString());
    }

    public void deleteByDeptId(Department dept) {
        UpdateWrapper<DepartmentMgr> uw = new UpdateWrapper<>();
        uw.lambda().eq(DepartmentMgr::getDeptId, dept.getId());
        remove(uw);
    }

    public void create(Department dept, User user) {
        DepartmentMgr deptMgr = new DepartmentMgr();
        deptMgr.setDeptId(dept.getId());
        deptMgr.setManagerId(user.getId());
        save(deptMgr);
    }

    /**
     * 变更部门主管
     * @param dept 部门对象
     * @param weComManagerIds 企业微信主管userid 列表
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void updateWeComDepartmentMgr(Department dept, List<String> weComManagerIds){
        deleteByDeptId( dept );
        StringBuilder deptMgrDesc = new StringBuilder();
        if ( CollectionUtil.isNotEmpty( weComManagerIds ) ) {
            for (String weComManagerId : weComManagerIds) {
                List<User> users = userService.checkIsWeComUserId( weComManagerId );
                if( CollectionUtil.isNotEmpty( users ) ){
                    for( User user : users ){
                        create(dept, user);
                        deptMgrDesc.append("[").append(user.getStaffName()).append("] ");
                    }
                }
            }
        }
        dept.setDeptMgrDesc(deptMgrDesc.toString());
    }

}
